<template>
	<view class="page">
		<view class="guaguaka-top">
			<image lazy-load="true"  class="top-bg" src="../../static/images/guaguaka-top.jpg" mode="widthFix"></image>
		</view>
		<view class="go-to-history" @click="goreHis">查看抽奖记录</view>
		<!-- <view class="go-to-home" @click="goHome">返回主页</view> -->
		<view class="guaguaka-box">
			<view class="yuanbao-rest">
				<image lazy-load="true"  class="yuanbao-bg" src="../../static/images/yuanbao-bg.png" mode="widthFix"></image>
				<text class="text">您还有{{user_info.virtual_money || 0}}元宝</text>
			</view>
			<view class="white-bg">
				<view class="canvas-box">
					<view style="position: relative;">
						<view id="gift" class="gift">{{gift_msg}}</view>
						<canvas class="canvas" @touchstart="start" @touchend="end" @touchmove="move" canvas-id="firstCanvas"></canvas>
					</view>
				</view>
			</view>
			
			<!-- <view class="winners">3分钟前王大锤获得了一等奖</view> -->
		</view>
		<!-- 活动规则 -->
		<view class="rule-box">
			<text class="title">活动规则</text>
			<view class="rules">
				<view class="rule-content">您可以在【幸运抽奖】中，消耗“元宝”参加此次刮奖活动。</view>
				<view class="rule-content">一、活动区域：</view>
				<view class="rule-content">成都美利亨材料城</view>
				<view class="rule-content">二、活动时间：</view>
				<view class="rule-content">活动时间：2019年11月18日-2019年11月22日；</view>
				<view class="rule-content">领奖截止时间：2019年11月22日  23：59：59</view>
				<view class="rule-content">三、活动咨询：</view>
				<view class="rule-content">您可以直接在【我的】-【在线客服】，咨询活动详情。</view>
				<view class="rule-content">四、活动内容：</view>
				<view class="rule-content">1、活动奖品：</view>
				<view class="rule-content">奖项一：微信红包刮刮乐，中奖率100%；</view>
				<view class="rule-content">注：每次抽奖将消耗5元宝。</view>
				<view class="rule-content">2、奖品领取方式及有效期：</view>
				<view class="rule-content">（1）活动期间刮开本涂层，即可获得红包奖品，红包直接发放至个人微信账户，请留意微信服务通知。</view>
				<view class="rule-content">（2）消费者抽奖所获微信红包，由微信支付发放，根据2017年2月10日微信最新规定“未实名及简化注册用户将无法再收取企业付款”，若您在一小时内未收到红包，请检查是否已按微信要求进行实名制。</view>
				<view class="rule-content">3、元宝领取方式：</view>
				<view class="rule-content">您可以通过以下方式，获得元宝：</view>
				<view class="rule-content">（1）分享商品：在商品详情页中，通过分享商品给好友或将商品海报转发到朋友圈，即可获得5个元宝奖励；</view>
				<view class="rule-content">（2）撰写笔记：在【分享专区】中，成功撰写一篇笔记，即可获得1个元宝奖励；</view>
				<view class="rule-content">（3）评论笔记：在【分享专区】中，成功评论一篇笔记，即可获得1个元宝奖励</view>
				<view class="rule-content">（4）分享笔记：在【分享专区】中，通过分享笔记给好友或将笔记海报转发到朋友圈，即可获得5个元宝奖励。</view>
				<view class="empty"></view>
				<view class="empty"></view>
			</view>
		</view>
		<view class="lotteryBox" v-if="lottery_box">
			<view class="bobox">
				<image lazy-load="true"  src="../../static/images/lottery_bg.png" mode="widthFix"></image>
				<view class="msg-box-2">
					<view class="msg-tit">恭喜您获得微信红包</view>
					<view class="msg-money">¥{{lottery_obj.price}}</view>
					<view class="msg-txt">已发放您的微信零钱</view>
					<view class="msg-sm">(未实名用户请先进行实名验证)</view>
					<view class="msg-btn-box">
						<image lazy-load="true"  @click="hideLotteryBox" src="../../static/images/ik.png" class="msg-btn"></image>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	var ctx;
	var sx = 0,
		sy = 0,
		perNum = 0;
	var giftWidth=0,giftHeight=0;	
	var canvasId = "firstCanvas";
	export default {
		data: function() {
			return {
				w: 300,
				h: 100,
				isfinish:false,
				isClear:false,
				user_info:[],
				gift_msg:'',
				is_lottery:false,
				lottery_box:false,
				lottery_obj:{},
				stauts_code:0,
				is_login:false
			}
		},
		onShow() {
			console.log(2)
			
			var self = this;
			setTimeout(function(){
				self.createCtx();
			},500);
			self.giftWidth();
			self.is_login = false;
			self.$request.request({
				url:'/user/info',
				success:function(res){
					self.stauts_code = res.code
					if(res.code==200){
						self.is_load = true;
						var  y = res.result;
						y.rebate_count = self.$money(y.rebate_count);
						self.user_info = y;
					}
				}
			});
			
			// #ifdef H5
			
			let share_time_line={
				title:self.$request.h5_share_name, // 分享标题
				link: self.$request.h5_share_url+'?page=guaguaka', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				imgUrl: self.$request.h5_img_url+'/static/images/logo.png', // 分享图标
			}
			let share_app_message={
				title: self.$request.h5_share_name, // 分享标题
				desc: '幸运抽奖，有机会抽到【奖品最大金额】元红包！', // 分享描述
				link: self.$request.h5_share_url+'?page=guaguaka', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				imgUrl: self.$request.h5_img_url+'/static/images/logo.png', // 分享图标
			}
			uni.setStorageSync('share_time_line',share_time_line);
			uni.setStorageSync('share_app_message',share_app_message);
			self.$request.wx_config()
			// #endif
		},
		onReady(){
			var self = this;
			self.createCtx();
			self.giftWidth();
		},
		onShareAppMessage(res) {
		    if (res.from === 'button') {
		      console.log(res.target)
		    }
		    return {
		      title: this.$request.share_title,
		      path: '/pages/index/index'
		    }
		  },
		methods: {
			giftWidth:function(){
				const query = uni.createSelectorQuery().in(this);
				query.select('#gift').boundingClientRect(data => {
					giftWidth=180;
					giftHeight=50;
				}).exec();
			},
			finish:function(){
				this.isfinish=true;
				this.is_lottery = true;
			},
			done:function(){
				
			},
			start: function(e) {
				if(this.user_info.virtual_money == 0){
					uni.showToast({
						title:'您的元宝不足，不能抽奖',
						icon:"none",
						duration:2000
					})
				}else{
					if(this.isfinish){
						if(!this.isClear){
							this.isClear=true;
							this.done();
							ctx.moveTo(0, 0);
							ctx.clearRect(0,0, 300, 100);
							ctx.stroke()
							ctx.draw(true);
						}					
						return false;
					} 
					sx = e.touches[0].x;
					sy = e.touches[0].y;
					console.log(e.touches[0].x + "  " + e.touches[0].y)
					this.getFilledPercentage();		
				}
			},
			end: function(e) {
				if(this.isfinish) return false;
			},
			move: function(e) {
				if(this.is_login) return;
				if(this.stauts_code == 40003){
					this.is_login = true;
					uni.navigateTo({
						url:'../login/login?page=guaguaka'
					})
				}else{
					if(this.user_info.virtual_money == 0){
						uni.showToast({
							title:'您的元宝不足，不能抽奖',
							icon:"none",
							duration:2000
						})
					}else{
						if(this.isfinish){
							if(!this.isClear){
								this.isClear=true;
								this.done();
								ctx.moveTo(0, 0);
								ctx.clearRect(0,0, 300, 100);
								ctx.stroke()
								ctx.draw(true);
							}					
							return false;
						} 
						ctx.moveTo(sx, sy);
						ctx.clearRect(sx, sy, 40, 40)
						ctx.stroke()
						ctx.globalAlpha = 0;
						ctx.draw(true);
						this.getFilledPercentage();
						sx = e.touches[0].x;
						sy = e.touches[0].y;
					}
				}
				
				
			},
			createCtx: function() {
				ctx = uni.createCanvasContext(canvasId);
				this.createRect();
			},
			createRect: function() {
				
				ctx.setFillStyle('#fe4e47')
				console.log(this.w)
				console.log(this.h)
				ctx.fillRect(0, 0, this.w, this.h);
				ctx.setTextAlign('left')    // 文字居中
				ctx.setFillStyle('#FFFFFF')  // 文字颜色：黑色
				ctx.setFontSize(20) 
				ctx.fillText('刮开此图层',75,32,300);
				ctx.draw();
			},
			hideLotteryBox(){
				this.lottery_box = false;
				uni.reLaunch({
				    url: 'guaguaka'
				});
			},
			goreHis(){
				if(this.stauts_code == 40003){
					uni.navigateTo({
						url:'../login/login?page=guaguaka'
					})
				}else{
					uni.navigateTo({
						url:'../reward-history/reward-history'
					})
				}
			},
			lottery(){
				var self = this;
				if(self.is_lottery) return;
				self.is_lottery = true;
				self.$request.request({
					url:'/user/luck_draw',
					success:function(res){
						if(res.code==200){
							self.is_load = true;
							var  y = res.result;
							y.price = self.$money(y.price );
							if(y.price==0){
								self.gift_msg = '很遗憾~您什么也没抽中';
								uni.showToast({
									title:'很遗憾~您什么也没抽中',
									icon:'none',
									duration:2000
								});
								setTimeout(function(){
									uni.reLaunch({
									    url: 'guaguaka'
									});
								},2500)
							}else{
								self.gift_msg = '恭喜您获得'+y.name;
								self.lottery_obj = y;
								setTimeout(function(){
									self.lottery_box = true;
								},1000)
							}
							
						}else if(res.code==40003){
							uni.navigateTo({
								url:'../login/login?page=guaguaka'
							})
						} else{
							self.gift_msg = res.msg
						}
					}
				});
			},
			goHome(){
				uni.redirectTo({
					url:"../index/index"
				})
			},
			getFilledPercentage: function() {
				var that=this;
				var cgiftWidth=giftWidth;
				var cgiftHeight=giftHeight;
				// #ifdef H5
					var cgiftWidth=giftWidth*2;
					var cgiftHeight=giftHeight*2;
				// #endif

				uni.canvasGetImageData({
					canvasId: canvasId,
					x: (that.w-giftWidth)/2-5,
					y: (that.h-giftHeight)/2-5,
					width: cgiftWidth,
					height: cgiftHeight,
					success: function(res) {
						let pixels = res.data;
						let transPixels = [];
						for (let i = 0; i < pixels.length; i += 4) {
							if (pixels[i + 3] < 128) {
								transPixels.push(pixels[i + 3]);
							}
						}
						perNum = (transPixels.length / (pixels.length / 4) * 100).toFixed(2);
						if(perNum>=50){
							that.lottery();
							that.finish();	
						}
					}
				});
			}
		}
	}
</script>

<style>
	@import url("guaguaka.css");
</style>
